//
//  JDNewOrderDetailViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2025/5/20.
//

import UIKit
import SwiftyJSON

class JDNewOrderDetailViewController: JDBaseViewController {

    var orderId: String?
    var shopName: String?
    var orderType: JDOrderType = .waitingPay
    var goodsDetailModel: JDOrderDetailModel?
    
    var currentCell: JDNewOrderDetailCell?
    
    var bottomToolBarContainerView: UIView?
    
    var rightFunButton: UIButton?
    var middleFunButton: UIButton?
    var leftFunButton: UIButton?
    
    var bottomTitleLabel: UILabel?
    var bottomPriceLabel: UILabel?
    
    var mainTableView: UITableView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = .commonColor()
        self.setupLeftBackItem()
        switch self.orderType {
        case .waitingPay:
            self.setupBackTitle("等待买家付款")
        case .alreadyPay:
            self.setupBackTitle("等待商家发货")
        case .sending:
            self.setupBackTitle("")
        case .pickup:
            self.setupBackTitle("等待已发货")
        case .completed:
            self.setupBackTitle("订单已完成")
        case .cancel:
            self.setupBackTitle("取消订单")
        case .refusse:
            self.setupBackTitle("商家拒单")
        case .settlement:
            self.setupNavigationTitle("结算")
        }
        
        self.setupBottomToolBar()
        self.setupUIElements()
        self.getNetData()
        // Do any additional setup after loading the view.
    }
    
    func setupBottomToolBar() {
        self.bottomToolBarContainerView = UIView()
        self.view.addSubview(self.bottomToolBarContainerView!)
        self.bottomToolBarContainerView?.snp.makeConstraints { make in
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(76)
        }
        self.bottomToolBarContainerView?.backgroundColor = .white
        
        
        if self.orderType == .waitingPay {
            // 待付款
            self.rightFunButton = UIButton(type: .custom)
            self.bottomToolBarContainerView?.addSubview(self.rightFunButton!)
            self.rightFunButton?.snp.makeConstraints { make in
                make.centerY.equalTo(self.bottomToolBarContainerView!)
                make.right.equalTo(self.bottomToolBarContainerView!).offset(-12)
                make.size.equalTo(CGSizeMake(82, 40))
            }
            self.rightFunButton?.makeCorner(20)
            self.rightFunButton?.buttonConfig(normalTitle: "支付", normalTitleColor: .white, titleFont: UIFont.systemFont(ofSize: 14, weight: .regular), backgroundColor: color("#FA6161"))
            self.rightFunButton?.addTarget(self, action: #selector(payAction), for: .touchUpInside)
            
//            self.middleFunButton = UIButton(type: .custom)
//            self.bottomToolBarContainerView?.addSubview(self.middleFunButton!)
//            self.middleFunButton?.snp.makeConstraints { make in
//                make.right.equalTo(self.rightFunButton!.snp.left).offset(-10)
//                make.size.equalTo(CGSizeMake(82, 40))
//                make.centerY.equalTo(self.bottomToolBarContainerView!)
//            }
//            self.middleFunButton?.makeCorner(20)
//            self.middleFunButton?.buttonConfig(normalTitle: "修改地址", normalTitleColor: color("#8D9198"), titleFont: UIFont.systemFont(ofSize: 14, weight: .regular), backgroundColor: color("#F5F6F8"))
//            
//            self.leftFunButton = UIButton(type: .custom)
//            self.bottomToolBarContainerView?.addSubview(self.leftFunButton!)
//            self.leftFunButton?.snp.makeConstraints { make in
//                make.centerY.equalTo(self.middleFunButton!)
//                make.right.equalTo(self.middleFunButton!.snp.left).offset(-14)
//            }
//            self.leftFunButton?.buttonConfig(normalTitle: "更多", normalImageNamed: "", normalTitleColor: color("#333333"), titleFont: UIFont.systemFont(ofSize: 14, weight: .regular))
//            
            
            self.bottomTitleLabel = UILabel()
            self.bottomToolBarContainerView?.addSubview(self.bottomTitleLabel!)
            self.bottomTitleLabel?.snp.makeConstraints { make in
                make.left.equalTo(self.bottomToolBarContainerView!).offset(12)
                make.bottom.equalTo(self.bottomToolBarContainerView!.snp.centerY).offset(-4-2)
            }
            self.bottomTitleLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
            self.bottomTitleLabel?.text = "合计"
            
            self.bottomPriceLabel = UILabel()
            self.bottomToolBarContainerView?.addSubview(self.bottomPriceLabel!)
            self.bottomPriceLabel?.snp.makeConstraints { make in
                make.left.equalTo(self.bottomToolBarContainerView!).offset(12)
                make.top.equalTo(self.bottomToolBarContainerView!.snp.centerY).offset(-2)
            }
            self.bottomPriceLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 12, weight: .regular), textColor: color("#FA6161"), numberOfLines: 1)
            self.bottomPriceLabel?.text = "￥990.0"
            
        } else if self.orderType == .alreadyPay {
            // 已接单
            // 待发货
            self.rightFunButton = UIButton(type: .custom)
            self.bottomToolBarContainerView?.addSubview(self.rightFunButton!)
            self.rightFunButton?.snp.makeConstraints { make in
                make.centerY.equalTo(self.bottomToolBarContainerView!)
                make.right.equalTo(self.bottomToolBarContainerView!).offset(-12)
                make.size.equalTo(CGSizeMake(82, 40))
            }
            self.rightFunButton?.makeCorner(20)
            self.rightFunButton?.buttonConfig(normalTitle: "查看物流", normalTitleColor: .white, titleFont: UIFont.systemFont(ofSize: 14, weight: .regular), backgroundColor: color("#8D9198"))
            self.rightFunButton?.addTarget(self, action: #selector(checkLogistics), for: .touchUpInside)
            
            self.middleFunButton = UIButton(type: .custom)
            self.bottomToolBarContainerView?.addSubview(self.middleFunButton!)
            self.middleFunButton?.snp.makeConstraints { make in
                make.right.equalTo(self.rightFunButton!.snp.left).offset(-10)
                make.size.equalTo(CGSizeMake(82, 40))
                make.centerY.equalTo(self.bottomToolBarContainerView!)
            }
            self.middleFunButton?.makeCorner(20)
            self.middleFunButton?.buttonConfig(normalTitle: "联系客服", normalTitleColor: color("#8D9198"), titleFont: UIFont.systemFont(ofSize: 14, weight: .regular), backgroundColor: color("#F5F6F8"))
            self.middleFunButton?.addTarget(self, action: #selector(contactCustomerServiceAction), for: .touchUpInside)
            
        } else if self.orderType == .pickup || self.orderType == .completed  {
            // 待取货  // 已完成
            self.rightFunButton = UIButton(type: .custom)
            self.bottomToolBarContainerView?.addSubview(self.rightFunButton!)
            self.rightFunButton?.snp.makeConstraints { make in
                make.centerY.equalTo(self.bottomToolBarContainerView!)
                make.right.equalTo(self.bottomToolBarContainerView!).offset(-12)
                make.size.equalTo(CGSizeMake(82, 40))
            }
            self.rightFunButton?.makeCorner(20)
            self.rightFunButton?.buttonConfig(normalTitle: "查看物流", normalTitleColor: .white, titleFont: UIFont.systemFont(ofSize: 14, weight: .regular), backgroundColor: color("#8D9198"))
            self.rightFunButton?.addTarget(self, action: #selector(checkLogistics), for: .touchUpInside)
            
            self.middleFunButton = UIButton(type: .custom)
            self.bottomToolBarContainerView?.addSubview(self.middleFunButton!)
            self.middleFunButton?.snp.makeConstraints { make in
                make.right.equalTo(self.rightFunButton!.snp.left).offset(-10)
                make.size.equalTo(CGSizeMake(82, 40))
                make.centerY.equalTo(self.bottomToolBarContainerView!)
            }
            self.middleFunButton?.makeCorner(20)
            self.middleFunButton?.buttonConfig(normalTitle: "联系客服", normalTitleColor: color("#8D9198"), titleFont: UIFont.systemFont(ofSize: 14, weight: .regular), backgroundColor: color("#F5F6F8"))
            self.middleFunButton?.addTarget(self, action: #selector(contactCustomerServiceAction), for: .touchUpInside)
            
        } else if self.orderType == .refusse {
            // 已拒单
             
            self.rightFunButton = UIButton(type: .custom)
            self.bottomToolBarContainerView?.addSubview(self.rightFunButton!)
            self.rightFunButton?.snp.makeConstraints { make in
                make.centerY.equalTo(self.bottomToolBarContainerView!)
                make.right.equalTo(self.bottomToolBarContainerView!).offset(-12)
                make.size.equalTo(CGSizeMake(82, 40))
            }
            self.rightFunButton?.makeCorner(20)
            self.rightFunButton?.buttonConfig(normalTitle: "联系客服", normalTitleColor: color("#8D9198"), titleFont: UIFont.systemFont(ofSize: 14, weight: .regular), backgroundColor: color("#F5F6F8"))
            self.rightFunButton?.addTarget(self, action: #selector(contactCustomerServiceAction), for: .touchUpInside)
        }
    }
    
    func setupUIElements() {
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints { make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
            make.bottom.equalTo(self.bottomToolBarContainerView!.snp.top)
        }
        self.mainTableView?.backgroundColor = .commonColor()
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.separatorStyle = .none
        self.mainTableView?.register(UITableViewCell.self, forCellReuseIdentifier: "topCell")
        self.mainTableView?.register(JDNewOrderDetailCell.self, forCellReuseIdentifier: "myCell")
        
//        if self.orderType == .waitingPay {
//            self.mainTableView?.tableHeaderView = self.setupTableViewHeaderViewWaitingPay()
//        } else if self.orderType == .refusse {
//            self.mainTableView?.tableHeaderView = self.setupTableViewHeaderViewRefuse()
//        }
    }
    
    func getNetData() {
        var params = [String: Any]()
        params["orderId"] = self.orderId
        
        if self.orderType == .waitingPay {
            // 待付款
        } else if self.orderType == .alreadyPay {
            // 已接单
        } else if self.orderType == .pickup {
            // 待取货
        } else if self.orderType == .completed {
            // 已完成
        } else if self.orderType == .refusse {
            // 已拒单
        }
        
        JDNetWorkRequest(.getOrderDetailInfo(params)) { responseStr in
//            {"msg":"ok","data":{"id":12,"orderTime":"2024-08-20 13:33:48","totalAmount":150000,"customerServicePhone":"0411-87979988","mobile":"13284231123","province":"辽宁省","freight":7500,"buyerName":"朱","orderNo":"JDCB1724132028350","receiverName":"朱","address":"华北路大湾市场","orderStatus":1,"city":"大连市","district":"甘井子区","postal":"116000","tariff":13500,"userMessage":"789","goodsList":[{"origin":"日本","goodsSpecificationNameList":[],"goodsName":"黑眼镜","goodsId":1,"goodsSpecificationIdList":[],"goodsBrand":"上下一白","goodsPriceText":"750.00","goodsMainImageUrl":"https:\/\/img11.360buyimg.com\/n1\/s450x450_jfs\/t1\/54403\/16\/24313\/48223\/669b4cd9F1f1e51e2\/91cdf0091dec0c68.jpg","goodsSkuId":1,"goodsPrice":150000,"goodsCount":5}],"buyerIdCardNumber":"456"},"code":0}
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                printLog("查询成功:\(responseStr)")
                
                
                // 新的接口内容
//                "{"code":"0","success":true,"data":{"goodsList":[{"goodsPrice":600000,"goodsSkuId":82,"specificationName":"100g","goodsBrand":"Dior","goodsSpecificationNameList":[],"goodsCount":1,"acceptOrderTime":null,"goodsPriceText":"600.00","goodsMainImageUrl":"9601d5b60349024178fb393a18c7da61966ed92fd1cba0e67b27c4cbf6b03eba","goodsSpecificationIdList":[],"goodsName":"产品测试商品不退商品","origin":"日本","consumptionTariff":0,"goodsId":52,"addedTariff":0}],"payTime":"2025-05-19 00:10:08","tariff":54600,"orderStatus":5,"arrivalTime":null,"province":"北京市","district":"东城区","orderConsumptionTariff":0,"shopName":"新增测试---供应商","orderAddedTariff":0,"orderType":null,"city":"北京市","buyerName":"朱林浩","postal":"116000","refusedReason":null,"userMessage":"","id":571,"orderNo":"JDCB1747584600480","deliveryTime":null,"freight":120140,"deliveryNo":null,"receiverName":"哦哦哦","mobile":"15041702096","customerServicePhone":"0411-84664438","totalAmount":774740,"orderTime":"2025-05-19 00:10:00","finishTime":null,"buyerIdCardNumber":"210802********1517","address":"啊哈哈哈"},"msg":"OK"}"

                if let model = JDOrderDetailModel.deserialize(from: responseStr, designatedPath: "data") {
                    self.goodsDetailModel = model
//                    var allGoodsPrice = 0.0
//                    for goodsModel in model.goodsList ?? [JDOrderDetailGoodsModel]() {
//                        allGoodsPrice = allGoodsPrice + JSON(goodsModel.goodsPrice as Any).doubleValue * JSON(goodsModel.goodsCount as Any).doubleValue
//                    }
                    self.bottomPriceLabel?.text = String.init(format: "￥%.2f", JSON(model.totalAmount as Any).doubleValue/1000.00) //String.init(format: "￥%.2f", (allGoodsPrice + JSON(model.tariff as Any).doubleValue + JSON(model.freight as Any).doubleValue)/1000.00)
                    self.bottomPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 18, weight: .semibold))
                }
            }
            self.mainTableView?.reloadData()
            
        } failure: { error in
            printLog("查询失败:\(error)")
            
        } error: { errorCode in
            printLog("查询错误:\(errorCode)")
            
        }

    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JDNewOrderDetailViewController {
    /// 查看物流
    @objc func checkLogistics() {
        
        let deliveryInfoVC = JDDeliveryInfoViewController()
        self.hidesBottomBarPushViewController(deliveryInfoVC)
    }
    
    /// 联系客服
    @objc func contactCustomerServiceAction() {
        
    }
    
    /// 支付事件
    @objc func payAction() {
        
        if self.currentCell?.paymentSelectedIndex == -1 {
            self.view.toast(message: "请选择支付方式")
            return
        }

        if self.currentCell?.paymentSelectedIndex == 1 {
            self.view.toast(message: "微信支付尚未开放，敬请期待")
            return
        }
        
        var params = [String: Any]()
        params["orderNo"] = self.goodsDetailModel?.orderNo
                    
        JDNetWorkRequest(.doOrderPay(params)) { responseStr in
            
            
            
            if self.currentCell?.paymentSelectedIndex == 0 {
                let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                if commonModel?.code == "0" {
                    let alipayStr = JSON(commonModel?.data as Any).dictionaryValue["orderStr"]?.stringValue ?? ""
                    JDAlipayManager.pay(alipayStr)
                }
            }
            
            if self.currentCell?.paymentSelectedIndex == 1 {
                // 微信支付
            }
        } failure: { error in
            print("付款错误:\(error)")
            
        } error: { errorCode in
            print("付款异常code:\(errorCode)")
        }
    }
    
    
}

extension JDNewOrderDetailViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "topCell")
             
            for subV in cell?.contentView.subviews ?? [UIView]() {
                subV.removeFromSuperview()
            }
            cell?.contentView.backgroundColor = .commonColor()
            if self.orderType == .waitingPay {
                
                let payHintLabel = JDPaddingLabel()
                cell?.contentView.addSubview(payHintLabel)
                payHintLabel.snp.makeConstraints { make in
                    make.left.equalTo(cell!.contentView).offset(12)
                    make.right.equalTo(cell!.contentView).offset(-12)
                    make.top.equalTo(cell!.contentView).offset(10)
                    make.height.equalTo(30)
                    make.bottom.equalTo(cell!.contentView)
                }
                payHintLabel.edgeInsets = .init(top: 0, left: 12, bottom: 0, right: 0)
                payHintLabel.backgroundColor = color("#FFF9F9")
                payHintLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 12, weight: .regular), textColor: color("#FA6161"), numberOfLines: 1)
                payHintLabel.text = " 订单将于15分钟后自动取消，请买家尽快完成付款。"
                payHintLabel.appendImgV("order_hint_image", at: 0)
            } else if self.orderType == .refusse {

                
                let subContainerView = UIView()
                cell?.contentView.addSubview(subContainerView)
                subContainerView.snp.makeConstraints { make in
                    make.left.equalTo(cell!.contentView).offset(12)
                    make.right.equalTo(cell!.contentView).offset(-12)
                    make.top.bottom.equalTo(cell!.contentView)
                }
                subContainerView.backgroundColor = .white
                subContainerView.makeCorner(6)
                
                let refusedReasonLabel = UILabel()
                subContainerView.addSubview(refusedReasonLabel)
                refusedReasonLabel.snp.makeConstraints { make in
                    make.left.equalTo(subContainerView).offset(12)
                    make.top.equalTo(subContainerView).offset(16)
                    make.height.equalTo(20)
                }
                refusedReasonLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .semibold), textColor: color("#FA6161"), numberOfLines: 1)
                refusedReasonLabel.text = "拒单理由 "
                refusedReasonLabel.appendImgV("order_refuse_image")

                let descriptionLabel = UILabel()
                
                subContainerView.addSubview(descriptionLabel)
                descriptionLabel.snp.makeConstraints { make in
                    make.left.equalTo(subContainerView).offset(12)
                    make.top.equalTo(refusedReasonLabel.snp.bottom).offset(6)
                    make.height.equalTo(20)
                    make.bottom.equalTo(subContainerView).offset(-16)
                }
                descriptionLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#FA6161"), numberOfLines: 1)
                descriptionLabel.text = "该商品现在暂无货，无法发货，全额退款。"
            }
            
            return cell!
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? JDNewOrderDetailCell
            
            self.currentCell = cell
            
            cell?.orderType = self.orderType
            cell?.shopName = self.shopName
            cell?.goodsDetailModel = self.goodsDetailModel
            cell?.reloadCurrentCell()
            return cell!
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            if self.orderType == .waitingPay || self.orderType == .refusse{
                return UITableView.automaticDimension
            }
            return 0
        } else if indexPath.row == 1 {
            return UITableView.automaticDimension
        }
        return 0
    }
    
}
